<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/2/23
 * Time: 10:37
 */

namespace app\common\helpers;


use think\Request;

class ImageUtil
{
    /**
     * @param string $url
     * @param string $samll_string //替换成缩略图
     * @return array
     * 单图  后端
     */
    public static function handle($url = "", $samll_string = false)
    {
        $preg = "/^http(s)?:\\/\\/.+/";
        if ($url && !preg_match($preg, $url) ) {
            if($samll_string){ //替换成缩略图
                $samll = str_replace('.','_'.$samll_string.'.',$url);
                if (file_exists(ROOT_PATH . 'public'.$samll)) {
                    $url = $samll;
                }
            }
            return  Request::instance()->domain() . $url;
        } else {
            return $url && ($url != "[]") ? $url : "";

        }
    }

    /**
     * @param string $url
     * @return array
     * 多图  后端
     */
    public static function handleMore($url, $domain = true)
    {
        $arr = [];
        $preg = "/^http(s)?:\\/\\/.+/";
        if ($url && !preg_match($preg, $url) && ($url != "[]")) {
            $url_list = explode(',',$url);
            if($url_list){
                foreach ($url_list as $v) {

                    $arr[] = $domain ? Request::instance()->domain(). $v : $v;
                }
            }
        }
        return $arr;
    }


    /**
     * 替换成缩略图
     */
    public static function replaceSmall($url){
        $pos = strrpos($url, '.');
        if($pos !== false)
        {
            $small = substr_replace($url, '_small.', $pos, strlen('.'));

            //去掉域名
            $small2 = str_replace(Request::instance()->domain(),'',$small);

            if (file_exists(ROOT_PATH . 'public'.$small2)) {
                return $small;
            }
        }
        return  $url;
    }

}